package com.cyber.app_container.controller;

import com.cyber.app_container.dto.Response;
import com.cyber.app_container.dto.UserDTO;
import com.cyber.app_container.entity.User;
import com.cyber.app_container.exception.ErrorCode;
import com.cyber.app_container.mapper.UserMapper;
import com.cyber.app_container.service.UserService;
import com.cyber.app_container.utils.JwtUtil;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final PasswordEncoder passwordEncoder;

    public AuthController(UserService userService, PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/register")
    public Response register(@Valid @RequestBody User user) {
        int length = user.getPassword().length();
        if (length < 8 || length > 32) {
            return Response.error(ErrorCode.PASSWORD_LENGTH_INVALID);
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.saveUser(user);
        return Response.success("注册成功");
    }

    @PostMapping("/login")
    public Response login(@RequestBody User user) {
        User existingUser = userService.findByUserName(user.getUserName());
        if (existingUser != null) {
            if (passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) {
                Map<String, String> dataMap = Map.of("token",
                        jwtUtil.generateToken(user.getUserName())
                );
                return Response.success(dataMap);
            } else {
                return Response.error(ErrorCode.CREDENTIALS_MISMATCH);
            }
        } else {
            return Response.error(ErrorCode.USER_NOT_FOUND);
        }

    }
}
